package com.atguigu.realtime.app.dwd;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.realtime.app.BaseApp;
import com.atguigu.realtime.util.MyKafkaUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.time.Duration;
import java.util.ArrayList;
import java.util.Comparator;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/4/17 9:18
 */
public class DWDLogApp extends BaseApp {
    public static void main(String[] args) {
        System.setProperty("HADOOP_USER_NAME", "atguigu");
        new DWDLogApp().init(2000, 2, "DWDLogApp", "DWDLogApp", "ods_log");
    }
    
    @Override
    protected void run(StreamExecutionEnvironment env,
                       DataStreamSource<String> sourceStream) {
        
        // 写业务逻辑
        //1. 区别新老客户
        SingleOutputStreamOperator<JSONObject> validateFlagStream = distinguishNewOrOld(sourceStream);
        // 2. 分流 页面日志  启动日志  曝光日志
        Tuple3<DataStream<JSONObject>, DataStream<JSONObject>, DataStream<JSONObject>> streams = splitStream(validateFlagStream);
        // 3. 分流后的数据写入到DWD(Kafka)
        sendToKafka(streams);
        
        
    }
    
    private void sendToKafka(Tuple3<DataStream<JSONObject>, DataStream<JSONObject>, DataStream<JSONObject>> streams) {
        streams
            .f0
            .map(obj -> JSON.toJSONString(obj))
            .addSink(MyKafkaUtil.getKafkaSink("dwd_start"));
    
        streams
            .f1
            .map(obj -> JSON.toJSONString(obj))
            .addSink(MyKafkaUtil.getKafkaSink("dwd_page"));
    
        streams
            .f2
            .map(obj -> JSON.toJSONString(obj))
            .addSink(MyKafkaUtil.getKafkaSink("dwd_display"));
    }
    
    private Tuple3<DataStream<JSONObject>, DataStream<JSONObject>, DataStream<JSONObject>> splitStream(SingleOutputStreamOperator<JSONObject> stream) {
        OutputTag<JSONObject> pageTag = new OutputTag<JSONObject>("page") {};
        OutputTag<JSONObject> displaysTag = new OutputTag<JSONObject>("displays") {};
        
        // 启动日志-> 主流  页面日志  曝光日志-> 侧输出流
        SingleOutputStreamOperator<JSONObject> main = stream
            .process(new ProcessFunction<JSONObject, JSONObject>() {
                @Override
                public void processElement(JSONObject data,
                                           Context ctx,
                                           Collector<JSONObject> out) throws Exception {
                    JSONObject startObj = data.getJSONObject("start");
                    
                    if (startObj != null) {
                        // 启动日志
                        out.collect(data);
                    } else {
                        // 页面日志
                        JSONObject pageObj = data.getJSONObject("page");
                        if (pageObj != null) {
                            ctx.output(pageTag, data);
                        }
                        
                        JSONArray displaysArr = data.getJSONArray("displays");
                        
                        if (displaysArr != null && displaysArr.size() > 0) {
                            for (int i = 0; i < displaysArr.size(); i++) {
                                JSONObject obj = displaysArr.getJSONObject(i);
                                obj.put("page_id", data.getJSONObject("page").getString("page_id"));
                                obj.put("ts", data.getLong("ts"));
                                obj.put("mid", data.getJSONObject("common").getString("mid"));
                                ctx.output(displaysTag, obj);
                            }
                            
                        }
                    }
                }
            });
        
        return Tuple3.of(main, main.getSideOutput(pageTag), main.getSideOutput(displaysTag));
        
    }
    
    /**
     * 区别新老客户.
     * 对common中的字段 is_new做一些修正
     * <p>
     * 如果是这个用户的第一条日志: is_new : 1
     * 否则 is_new: 0
     *
     * @param sourceStream
     * @return
     */
    private SingleOutputStreamOperator<JSONObject> distinguishNewOrOld(DataStreamSource<String> sourceStream) {
        // 1. 给数据加水印
        // 2. 加窗口
        // 3. 窗口内进行判断是否第一个
        return sourceStream
            .map(JSON::parseObject)
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((obj, ts) -> obj.getLong("ts"))
            )
            .keyBy(obj -> obj.getJSONObject("common").getString("mid"))
            .window(TumblingEventTimeWindows.of(Time.seconds(5)))
            .process(new ProcessWindowFunction<JSONObject, JSONObject, String, TimeWindow>() {
                
                private ValueState<Long> firstVisitState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    firstVisitState = getRuntimeContext().getState(new ValueStateDescriptor<Long>("firstVisitState", Long.class));
                }
                
                @Override
                public void process(String key,
                                    Context context,
                                    Iterable<JSONObject> elements,
                                    Collector<JSONObject> out) throws Exception {
                    // 新老用户的确认
                    
                    // mid_1 : 如果是这个设备id的第一个窗口(排序), 新用户, 否则老用户
                    if (firstVisitState.value() == null) {
                        // 按照时间戳升序排列, 把第一个的is_new 设置1 其他设置为0
                        ArrayList<JSONObject> list = new ArrayList<>();
                        for (JSONObject obj : elements) {
                            list.add(obj);
                        }
                        //                        list.sort((o1, o2) -> o1.getLong("ts").compareTo(o2.getLong("ts")));
                        list.sort(Comparator.comparing(o -> o.getLong("ts")));
                        
                        for (int i = 0; i < list.size(); i++) {
                            if (i == 0) {
                                list.get(i).getJSONObject("common").put("is_new", "1");
                                firstVisitState.update(list.get(i).getLong("ts")); // 更新状态
                            } else {
                                list.get(i).getJSONObject("common").put("is_new", "0");
                            }
                            out.collect(list.get(i));
                        }
                        
                    } else {
                        // 不是第一个窗口, 每个 is_new 设置0
                        for (JSONObject obj : elements) {
                            obj.getJSONObject("common").put("is_new", "0");
                            out.collect(obj);
                        }
                    }
                }
            });
        
    }
}
